<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>RPC</title>
  <link href="../Styles/stylesheet.css" rel="stylesheet" type="text/css" />
  <script src="../toc.js" type="text/javascript">



  //<![CDATA[

   <!-- empty -->
  //]]>
  </script>
  <script type="text/javascript">




  /* <![CDATA[ */
    (function() {
        var s = document.createElement("script"), t = document.getElementsByTagName("script")[0];
        s.type = "text/javascript";
        s.async = true;
        s.src = "http://api.flattr.com/js/0.6/load.js?mode=auto";
        t.parentNode.insertBefore(s, t);
    })();
  /* ]]> */
  </script>
  <style type="text/css">
/*<![CDATA[*/

  body { counter-reset: chapter 13; }

  a.sgc-9 {display:none;}
  span.sgc-8 {color: firebrick}
  span.sgc-7 {color: black}
  span.sgc-6 {color: green}
  span.sgc-5 {color: darkmagenta}
  span.sgc-4 {color: blue}
  span.sgc-3 {color: DarkRed}
  span.sgc-2 {color: purple}
  span.sgc-1 {color: darkred}
  /*]]>*/
  </style>
</head>

<body>
  <div class="chapter">
    <h1 id="heading_id_2" class="en">Remote Procedure Call</h1>
    <h1 id="heading_id_2" class="zh">远程过程调用<h1>
  </div>

  <div class="preface"></div>

  <div class="generate_from_h2" id="generated-toc"></div>

  <h2 id="heading_id_3" class="en">Introduction</h2>
  <h2 id="heading_id_3" class="zh">介绍</h2>
  <p class="en">Socket and HTTP programming use a message-passing paradigm. A client sends a message to a server which usually sends a message back. Both sides are responsible for creating messages in a format understood by both sides, and in reading the data out of those messages.</p>
  <p class="zh">Socket 和 HTTP 编程 使用的是一种消息传递模式. 一个客户端发送了一个消息给服务器，通常会等回一个响应消息。两边都要创建出一种双方可理解的格式，然后从里面读出数据的实体。</p>

  <p class="en">However, most standalone applications do not make so much use of message passing techniques. Generally the preferred mechanism is that of the <code>function</code> (or method or procedure) call. In this style, a program will call a function with a list of parameters, and on completion of the function call will have a set of return values. These values may be the function value, or if addresses have been passed as parameters then the contents of those addresses might have been changed.</p>
  <p class="zh"> 然而，大多数独立主机应用不会做太多的消息传递技术。一般来说，<code>函数调用</code>(或者被称作method/procedure)的使用更为普遍。在函数风格下，程序会调用函数时会传入一系列参数，然后函数调用完毕后会返回一系列返回值。这些返回值会成为函数的值，或者传递进函数的是参数的地址引用，那么参数值可能最后会被修改。</p>
  <p class="en">The remote procedure call is an attempt to bring this style of programming into the network world. Thus a client will make what looks to it like a normal procedure call. The client-side will package this into a network message and transfer it to the server. The server will unpack this and turn it back into a procedure call on the server side. The results of this call will be packaged up for return to the client.</p>
  <p class="zh">远程过程调用的初衷就是把这种风格带入网络世界。客户调用时候会让这一切看起来像是函数调用，而客户端会打包这些数据成为消息，然后传递到远端服务器。服务器再拆解包，然后把它变成在服务器端的过程调用，而最后的返回结果会被打包传回给客户。</p>

  <p class="en">Diagrammatically it looks like<br />
  <img alt="" src="../Images/rpc_stub.png" /><br />
  where the steps are</p>

  <p class="zh">用图示表示的话，看起来就会是这个样子<br />
  <img alt="" src="../Images/rpc_stub.png" /><br />
  经历如下几个步骤</p>

  <ol class="en">
    <li>The client calls the local stub procedure. The stub packages up the parameters into a network message. This is called <i>marshalling</i>.</li>

    <li>Networking functions in the O/S kernel are called by the stub to send the message.</li>

    <li>The kernel sends the message(s) to the remote system. This may be connection-oriented or connectionless.</li>

    <li>A server stub unmarshals the arguments from the network message.</li>

    <li>The server stub executes a local procedure call.</li>

    <li>The procedure completes, returning execution to the server stub.</li>

    <li>The server stub marshals the return values into a network message.</li>

    <li>The return messages are sent back.</li>

    <li>The client stub reads the messages using the network functions.</li>

    <li>The message is unmarshalled. and the return values are set on the stack for the local process.</li>
  </ol>
    <ol class="zh">
    <li>客户调用本地存根节点过程, 存根节点会把参数打包成网络消息，这个过程被称为<i>编组</i></li>
    
    <li>OS内核里的网络通信函数会被存根节点调用来发送消息。</li>

    <li>内核把消息传递给远端系统。这个可以使面向连接的或者是无连接传输模式。</li>

    <li>服务器端的存根节点会把参数从网络消息中拆解出来。</li>

    <li>服务器端的存根节点会执行一个本地过程调用</li>

    <li>等到过程完成，返回之行结果给服务器端的存根节点。</li>

    <li>服务器存根节点会把返回值编组成网络消息。</li>

    <li>消息被返回</li>

    <li>客户端存根节点用网络通信函数读取消息</li>

    <li>消息被拆解。然后返回值被放到本地程序的堆栈内。</li>
  </ol>


  <p class="en">There are two common styles for implementing RPC. The first is typified by Sun's RPC/ONC and by CORBA. In this, a specification of the service is given in some abstract language such as CORBA IDL (interface definition language). This is then compiled into code for the client and for the server. The client then writes a normal program containing calls to a procedure/function/method which is linked to the generated client-side code. The server-side code is actually a server itself, which is linked to the procedure implementation that you write.</p>
  <p class="zh">远程过程调用有两种普遍使用的风格。第一个是以SUN开发的CORBA的RPC/ONC为代表。这里，服务的描述被某种像CORBA IDL(接口定义语言)抽象语言提供，然后编译成可执行代码分别部署在client端和server端。客户接着就可以写一个常规的程序去连接那个生成出来的方法,而server端的代码实际上就是server服务的实体，然后连接到你实现的程序。

  <p class="en">In this way, the client-side code is almost identical in appearance to a normal procedure call. Generally there is a little extra code to locate the server. In Sun's ONC, the address of the server must be known; in CORBA a naming service is called to find the address of the server; In Java RMI, the IDL is Java itself and a naming service is used to find the address of the service.</p>
  <p class="zh">这样，客户端代码就基本上跟一个普通的程序调用没什么区别了。一般来说，在server端部署的代码量会有点多。在SUN开发的的ONC上，server端的地址必须是公开的。在CORBA里面，一个命名服务会启动去寻找服务器的地址。而在JAVA RMI中，IDL由Java类库实现，然后命名服务会被调用去寻找服务器地址。</p>

  <p class="en">In the second style, you have to make use of a special client API. You hand the function name and its parameters to this library on the client side. On the server side, you have to explicitly write the server yourself, as well as the remote procedure implementation.</p>
  <p class="zh">在第二种风格中，你会用到一些特别的client端API，这些API，包括函数名，和参数是在生成的client代码中的。与此不同的是，在server端，你必须用你的手把代码敲出来，包括这些远程函数的实现。</p>

  <p class="en">This approach is used by many RPC systems, such as Web Services. It is also the approach used by Go's RPC.</p>
  <p class="zh">很多RPC系统都采用了这种方法，比如Web Services. 当然，Go的PRC也采用了这样的方法。

  <h2 id="heading_id_4" class="en">Go RPC</h2>
  <h2 id="heading_id_4" class="zh">Go RPC</h2>

  <p class="en">Go's RPC is so far unique to Go. It is different to the other RPC systems, so a Go client will only talk to a Go server. It uses the Gob serialisation system discussed in chapter X, which defines the data types which can be used.</p>
  <p class="zh">Go的RPC是非常独特的。它与别的RPC系统不同，所以Go的client只能跟Go的server对话。它被用在第十章讨论的Gob序列化系统里面，用来定义可被使用的数据类型。</p>

  <p class="en">RPC systems generally make some restrictions on the functions that can be called across the network. This is so that the RPC system can properly determine what are value arguments to be sent, what are reference arguments to receive answers, and how to signal errors.</p>
  <p class="zh">RPC系统一般来说是对远程的函数调用的一些限定。这也就是为什么RPC系统可以恰当地决定哪些参数要被传递，哪些引用参数来接受数据，以及如何做错误警报。</p>

  <ul class="en">
    <li>the function must be public (begin with a capital letter);</li>

    <li>have exactly two arguments, the first is a pointer to value data to be received by the function from the client, and the second is a pointer to hold the answers to be returned to the client; and</li>

    <li>have a return value of type <code>os.Error</code></li>
  </ul>
  <ul class="zh">
    <li>函数必须是公共的(也就是首字母大写)</li>

    <li>有且仅有2个指针参数，第一个指向 “接收器”——接受从client端发过来的数据值，第二个指向 "发送器"——存放向client端发送的返回值。</li>

    <li>有一个<code>os.Error</code>类型返回值 </li>
  </ul>

  <p class="en">For example, a valid function is</p>
  <p class="zh">比方说，一个合法的函数应该是如下这样的</p>  
  <pre><code>
      F(&amp;T1, &amp;T2) os.Error
    </code></pre>

  <p class="en">The restriction on arguments means that you typically have to define a structure type. Go's RPC uses the <code>gob</code> package for marshalling and unmarshalling data, so the argument types have to follow the rules of <code>gob</code> as discussed in an earlier chapter.</p>
  <p class="zh">所谓的对参数的限定指的是你只需要定义数据类型。Go的RPC会用<code>gob</code> 包来编组和解编组数据，所以对于参数类型，你只需要按照之前讨论过的<code>gob</code>的规则定义就可以。</p>


  <p class="en">We shall follow the example given in the Go documentation, as this illustrates the important points. The server performs two operations which are trivial - they do not require the "grunt" of RPC, but are simple to understand. The two operations are to multiply two integers, and the second is to find the quotient and remainder after dividing the first by the second.</p>
  <p class="zh">我们应该参考Go的官方文档的例子，因为这些例子展示了一些关键点。Server端执行2种操作，这些操作看起来非常浅显易懂，这里没用RPC的那些难懂的细节，而是非常易于理解。 第一种操作是两个整数相乘，第二个则是第一个数字除以第二个数字然后求商取余。</p>

  <p class="en">The two values to be manipulated are given in a structure:</p>
  <p class="zh">2个操作数被放在了一个结构体里：</p>
  <pre><code>
type Values struct {
    X, Y int
}
    </code></pre>

  <p class="en">The sum is just an <code>int</code>, while the quotient/remainder is another structure</p>
  <p class="zh">两数之和是一个 <code>int</code>, 而商数和余数则在另一个结构体里</p>
  <pre><code>
type Quotient struct {
    Quo, Rem int
}
    </code></pre>

  <p class="en">We will have two functions, multiply and divide to be callable on the RPC server. These functions will need to be registered with the RPC system. The function <code>Register</code> takes a single parameter, which is an interface. So we need a type with these two functions:</p>
  <p class="zh">我们会把这两个程序，也就是乘法和除法, 部署在RPC的server端等待调用。这些函数过会儿会被注册到RPC系统里去。函数<code>Register</code>会带一个interface类型的参数。 所以我们要给这两个函数定义一个类型。</p>
  <pre><code>
type Arith int

func (t *Arith) Multiply(args *Args, reply *int) os.Error {
        *reply = args.A * args.B
        return nil
}

func (t *Arith) Divide(args *Args, quo *Quotient) os.Error {
        if args.B == 0 {
                return os.ErrorString("divide by zero")
        }
        quo.Quo = args.A / args.B
        quo.Rem = args.A % args.B
        return nil
}
    </code></pre>

  <p class="en">The underlying type of <code>Arith</code> is given as <code>int</code>. That doesn't matter - any type could have done.</p>
  <p class="zh"><code>Arith</code>背后的实际类型是 <code>int</code>. 这不要紧 - 任何类型都可以。</p>

  <p class="en">An object of this type can now be registered using <code>Register</code>, and then its methods can be called by the RPC system.</p>
  <p class="zh">这个类型的对象现在可以用<code>Register</code>函数来注册, 之后，RPC系统就可以调用这个方法了。</p>

  <h3 id="heading_id_5" class="en">HTTP RPC Server</h3>
  <h3 id="heading_id_5" class="zh">HTTP RPC 服务器</h3>

  <p class="en">Any RPC needs a transport mechanism to get messages across the network. Go can use HTTP or TCP. The advantage of the HTTP mechanism is that it can leverage off the HTTP suport library. You need to add an RPC handler to the HTTP layer which is done using <code>HandleHTTP</code> and then start an HTTP server. The complete code is</p>
  <p class="zh">任何RPC系统都需要一个传输机制来跨网络地传递消息。Go可以用HTTP或TCP。用HTTP机制的优势就是可以借助HTTP来支持库文件。 你需要通过<code>HandleHTTP</code>在HTTP层上加一个RPC处理器， 然后启动一个HTTP 服务器。完整的代码是这样</p>
  <pre><code><span class="sgc-7">
<span class="sgc-1">/**
* ArithServer
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"net/rpc"</span>
        <span class="sgc-3">"errors"</span>
        <span class="sgc-3">"net/http"</span>
)

<span class="sgc-2">type</span> <span class="sgc-4">Args</span> <span class="sgc-2">struct</span> {
        <span class="sgc-5">A</span>, <span class="sgc-5">B</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Quotient</span> <span class="sgc-2">struct</span> {
        <span class="sgc-4">Quo</span>, <span class="sgc-4">Rem</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Arith</span> <span class="sgc-6">int</span>

<span class="sgc-2">func</span> (t *<span class="sgc-4">Arith</span>) <span class="sgc-4">Multiply</span>(args *<span class="sgc-4">Args</span>, reply *<span class="sgc-6">int</span>) error {
        *reply = args.<span class="sgc-5">A</span> * args.<span class="sgc-5">B</span>
        <span class="sgc-2">return</span> nil
}

<span class="sgc-2">func</span> (t *<span class="sgc-4">Arith</span>) <span class="sgc-4">Divide</span>(args *<span class="sgc-4">Args</span>, quo *<span class="sgc-4">Quotient</span>) error {
        <span class="sgc-2">if</span> args.<span class="sgc-5">B</span> == 0 {
                <span class="sgc-2">return</span> errors.<span class="sgc-4">New</span>(<span class="sgc-3">"divide by zero"</span>)
        }
        quo.<span class="sgc-4">Quo</span> = args.<span class="sgc-5">A</span> / args.<span class="sgc-5">B</span>
        quo.<span class="sgc-4">Rem</span> = args.<span class="sgc-5">A</span> % args.<span class="sgc-5">B</span>
        <span class="sgc-2">return</span> nil
}

<span class="sgc-2">func</span> main() {

        arith := <span class="sgc-2">new</span>(<span class="sgc-4">Arith</span>)
        rpc.<span class="sgc-4">Register</span>(arith)
        rpc.<span class="sgc-4">HandleHTTP</span>()

        err := http.<span class="sgc-4">ListenAndServe</span>(<span class="sgc-3">":1234"</span>, nil)
        <span class="sgc-2">if</span> err != nil {
                fmt.<span class="sgc-4">Println</span>(err.<span class="sgc-4">Error</span>())
        }
}
</span></code></pre>

  <h3 id="heading_id_6" class="en">HTTP RPC client</h3>
  <h3 id="heading_id_6" class="zh">HTTP RPC 客户端</h3>

  <p class="en">The client needs to set up an HTTP connection to the RPC server. It needs to prepare a structure with the values to be sent, and the address of a variable to store the results in. Then it can make a <code>Call</code> with arguments:</p>
  <p class="zh">客户端需要设置一个HTTP连接，来连接RPC服务器。客户端需要发起一个对RPC服务器的连接。它需要准备一个包含要发送数据的结构体, 以及一个接受返回值的变量地址。之后，它就可以用参数来 <code>调用</code>了，参数如下 </p>

  <ul class="en">
    <li>The name of the remote function to execute</li>

    <li>The values to be sent</li>

    <li>The address of a variable to store the result in</li>
  </ul>
    <ul class="zh">
    <li>想要调用的远程函数的名字</li>

    <li>被发送的数据结构体</li>

    <li>储存返回值的变量地址</li>
  </ul>

  <p class="en">A client that calls both functions of the arithmetic server is</p>
  <p class="zh">一个调用在远端服务器上的这两个计算函数的客户端是这样的</p>
  <pre><code><span class="sgc-7">
<span class="sgc-1">/**
* ArithClient
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"net/rpc"</span>
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"log"</span>
        <span class="sgc-3">"os"</span>
)

<span class="sgc-2">type</span> <span class="sgc-4">Args</span> <span class="sgc-2">struct</span> {
        <span class="sgc-5">A</span>, <span class="sgc-5">B</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Quotient</span> <span class="sgc-2">struct</span> {
        <span class="sgc-4">Quo</span>, <span class="sgc-4">Rem</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">func</span> main() {
        <span class="sgc-2">if</span> len(os.<span class="sgc-4">Args</span>) != 2 {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Usage: "</span>, os.<span class="sgc-4">Args</span>[0], <span class="sgc-3">"server"</span>)
                os.<span class="sgc-4">Exit</span>(1)
        }
        serverAddress := os.<span class="sgc-4">Args</span>[1]

        client, err := rpc.<span class="sgc-4">DialHTTP</span>(<span class="sgc-3">"tcp"</span>, serverAddress+<span class="sgc-3">":1234"</span>)
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"dialing:"</span>, err)
        }
        <span class="sgc-8">// Synchronous call
</span> args := <span class="sgc-4">Args</span>{17, 8}
        <span class="sgc-2">var</span> reply <span class="sgc-6">int</span>
        err = client.<span class="sgc-4">Call</span>(<span class="sgc-3">"Arith.Multiply"</span>, args, &amp;reply)
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"arith error:"</span>, err)
        }
        fmt.<span class="sgc-4">Printf</span>(<span class="sgc-3">"Arith: %d*%d=%d\n"</span>, args.<span class="sgc-5">A</span>, args.<span class="sgc-5">B</span>, reply)

        <span class="sgc-2">var</span> quot <span class="sgc-4">Quotient</span>
        err = client.<span class="sgc-4">Call</span>(<span class="sgc-3">"Arith.Divide"</span>, args, ")
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"arith error:"</span>, err)
        }
        fmt.<span class="sgc-4">Printf</span>(<span class="sgc-3">"Arith: %d/%d=%d remainder %d\n"</span>, args.<span class="sgc-5">A</span>, args.<span class="sgc-5">B</span>, quot.<span class="sgc-4">Quo</span>, quot.<span class="sgc-4">Rem</span>)

}
</span></code></pre>

  <h3 id="heading_id_7" class="en">TCP RPC server</h3>
  <h3 id="heading_id_7" class="zh">TCP RPC 服务端</h3>

  <p class="en">A version of the server that uses TCP sockets is</p>
  <p class="zh">一个使用TCP socket的服务器是这样的</p>

  <pre><code><span class="sgc-7">
<span class="sgc-1">/**
* TCPArithServer
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"net/rpc"</span>
        <span class="sgc-3">"errors"</span>
        <span class="sgc-3">"net"</span>
        <span class="sgc-3">"os"</span>
)

<span class="sgc-2">type</span> <span class="sgc-4">Args</span> <span class="sgc-2">struct</span> {
        <span class="sgc-5">A</span>, <span class="sgc-5">B</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Quotient</span> <span class="sgc-2">struct</span> {
        <span class="sgc-4">Quo</span>, <span class="sgc-4">Rem</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Arith</span> <span class="sgc-6">int</span>

<span class="sgc-2">func</span> (t *<span class="sgc-4">Arith</span>) <span class="sgc-4">Multiply</span>(args *<span class="sgc-4">Args</span>, reply *<span class="sgc-6">int</span>) error {
        *reply = args.<span class="sgc-5">A</span> * args.<span class="sgc-5">B</span>
        <span class="sgc-2">return</span> nil
}

<span class="sgc-2">func</span> (t *<span class="sgc-4">Arith</span>) <span class="sgc-4">Divide</span>(args *<span class="sgc-4">Args</span>, quo *<span class="sgc-4">Quotient</span>) error {
        <span class="sgc-2">if</span> args.<span class="sgc-5">B</span> == 0 {
                <span class="sgc-2">return</span> errors.<span class="sgc-4">New</span>(<span class="sgc-3">"divide by zero"</span>)
        }
        quo.<span class="sgc-4">Quo</span> = args.<span class="sgc-5">A</span> / args.<span class="sgc-5">B</span>
        quo.<span class="sgc-4">Rem</span> = args.<span class="sgc-5">A</span> % args.<span class="sgc-5">B</span>
        <span class="sgc-2">return</span> nil
}

<span class="sgc-2">func</span> main() {

        arith := <span class="sgc-2">new</span>(<span class="sgc-4">Arith</span>)
        rpc.<span class="sgc-4">Register</span>(arith)

        tcpAddr, err := net.<span class="sgc-4">ResolveTCPAddr</span>(<span class="sgc-3">"tcp"</span>, <span class="sgc-3">":1234"</span>)
        checkError(err)

        listener, err := net.<span class="sgc-4">ListenTCP</span>(<span class="sgc-3">"tcp"</span>, tcpAddr)
        checkError(err)

<span class="sgc-8">        /* This works:
        rpc.Accept(listener)
        */
</span><span class="sgc-8"> /* and so does this:
         */
</span> <span class="sgc-2">for</span> {
                conn, err := listener.<span class="sgc-4">Accept</span>()
                <span class="sgc-2">if</span> err != nil {
                        <span class="sgc-2">continue</span>
                }
                rpc.<span class="sgc-4">ServeConn</span>(conn)
        }

}

<span class="sgc-2">func</span> checkError(err error) {
        <span class="sgc-2">if</span> err != nil {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Fatal error "</span>, err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(1)
        }
}
</span></code></pre>

  <p class="en">Note that the call to <code>Accept</code> is blocking, and just handles client connections. If the server wishes to do other work as well, it should call this in a goroutine.</p>
  <p class="zh">留心一点，对于<code>Accept</code>的调用是阻塞式的，用来处理客户端连接。如果服务端希望也做点别的事情，那么就应该在goroutine中调用它。</p>

  <h3 id="heading_id_8" class="en">TCP RPC client</h3>
  <h3 id="heading_id_8" class="zh">TCP RPC 客户端</h3>

  <p>A client that uses the TCP server and calls both functions of the arithmetic server is</p>
  <p>一个使用TCP连接，调用在远端计算服务器的两个函数的客户端是这样的。</p>  
  <pre><code><span class="sgc-7">
<span class="sgc-1">/**
* TCPArithClient
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"net/rpc"</span>
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"log"</span>
        <span class="sgc-3">"os"</span>
)

<span class="sgc-2">type</span> <span class="sgc-4">Args</span> <span class="sgc-2">struct</span> {
        <span class="sgc-5">A</span>, <span class="sgc-5">B</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Quotient</span> <span class="sgc-2">struct</span> {
        <span class="sgc-4">Quo</span>, <span class="sgc-4">Rem</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">func</span> main() {
        <span class="sgc-2">if</span> len(os.<span class="sgc-4">Args</span>) != 2 {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Usage: "</span>, os.<span class="sgc-4">Args</span>[0], <span class="sgc-3">"server:port"</span>)
                os.<span class="sgc-4">Exit</span>(1)
        }
        service := os.<span class="sgc-4">Args</span>[1]

        client, err := rpc.<span class="sgc-4">Dial</span>(<span class="sgc-3">"tcp"</span>, service)
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"dialing:"</span>, err)
        }
        <span class="sgc-8">// Synchronous call
</span> args := <span class="sgc-4">Args</span>{17, 8}
        <span class="sgc-2">var</span> reply <span class="sgc-6">int</span>
        err = client.<span class="sgc-4">Call</span>(<span class="sgc-3">"Arith.Multiply"</span>, args, &amp;reply)
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"arith error:"</span>, err)
        }
        fmt.<span class="sgc-4">Printf</span>(<span class="sgc-3">"Arith: %d*%d=%d\n"</span>, args.<span class="sgc-5">A</span>, args.<span class="sgc-5">B</span>, reply)

        <span class="sgc-2">var</span> quot <span class="sgc-4">Quotient</span>
        err = client.<span class="sgc-4">Call</span>(<span class="sgc-3">"Arith.Divide"</span>, args, ")
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"arith error:"</span>, err)
        }
        fmt.<span class="sgc-4">Printf</span>(<span class="sgc-3">"Arith: %d/%d=%d remainder %d\n"</span>, args.<span class="sgc-5">A</span>, args.<span class="sgc-5">B</span>, quot.<span class="sgc-4">Quo</span>, quot.<span class="sgc-4">Rem</span>)

}
</span></code></pre>

  <h3 id="heading_id_9" class="en">Matching values</h3>
  <h3 id="heading_id_9" class="zh">数据值匹配</h3>

  <p class="en">We note that the types of the value arguments are not the same on the client and server. In the server, we have used <code>Values</code> while in the client we used <code>Args</code>. That doesn't matter, as we are following the rules of <code>gob</code> serialisation, and the names an types of the two structures' fields match. Better programming practise would say that the names should be the same!*</p>
  <p class="zh">我们注意到在server端和client端的数据类型并不相同。在服务器端，我们用的是<code>Values</code> 而在客户端我们用了 <code>Args</code>。这并不成问题，因为我们按照了<code>gob</code>串行化规则，而且在两个结构体字段中的名称能匹配。但更好的编程实践却告诉我们，名字也应该相同。*</p>

  <p class="en">However, this does point out a possible trap in using Go RPC. If we change the structure in the client to be, say,</p>
  <p class="zh">然而，这指出了go中可能存在的陷阱的可能性。要是我们改变了client端的结构体，比方说，</p>
  <pre><code>
type Values struct {
        C, B int
}
    </code></pre>

  <p class="en">then <code>gob</code> has no problems: on the server-side the unmarshalling will ignore the value of <code>C</code> given by the client, and use the default zero value for <code>A</code>.</p>
  <p class="zh">而这对于 <code>gob</code> 来说却没有什么疑问: 在server端解编组的时候会忽略来自client的<code>C</code>,然后将默认值零值赋给<code>A</code>.</p>

  <p class="en">Using Go RPC will require a rigid enforcement of the stability of field names and types by the programmer. We note that there is no version control mechanism to do this, and no mechanism in <code>gob</code> to signal any possible mismatches.</p>
  <p class="zh">用Go RPC会要求对字段名称和类型的一致性都进行严格加强。我们注意到，没有任何的版本控制机制或是<code>gob</code>本身，都没有任何提示数据不匹配的保护机制。 </p>

  <h2 id="heading_id_10" class="en">JSON</h2>
  <h2 id="heading_id_10" class="zh">JSON</h2>

  <p class="en">This section adds nothing new to the earlier concepts. It just uses a different "wire" format for the data, JSON instead of <code>gob</code>. As such, clients or servers could be written in other language that understand sockets and JSON.</p>
  <p class="zh">这部分每增加什么新的概念。只是用了另一种数据的 "电报" 格式， 用JSON来代替<code>gob</code>。由于这样做了，那么client端和server端要用另一种语言来来理解socket和JSON。</p>

  <h3 id="heading_id_11" class="en">JSON RPC client</h3>
  <h3 id="heading_id_11" class="zh">JSON RPC 客户端</h3>

  <p class="en">A client that calls both functions of the arithmetic server is</p>
  <p class="zh">客户端调用计算服务器的两个函数如下</p>
  <pre><code><span class="sgc-7">
<span class="sgc-8">/* JSONArithCLient
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"net/rpc/jsonrpc"</span>
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"log"</span>
        <span class="sgc-3">"os"</span>
)

<span class="sgc-2">type</span> <span class="sgc-4">Args</span> <span class="sgc-2">struct</span> {
        <span class="sgc-5">A</span>, <span class="sgc-5">B</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Quotient</span> <span class="sgc-2">struct</span> {
        <span class="sgc-4">Quo</span>, <span class="sgc-4">Rem</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">func</span> main() {
        <span class="sgc-2">if</span> len(os.<span class="sgc-4">Args</span>) != 2 {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Usage: "</span>, os.<span class="sgc-4">Args</span>[0], <span class="sgc-3">"server:port"</span>)
                log.<span class="sgc-4">Fatal</span>(1)
        }
        service := os.<span class="sgc-4">Args</span>[1]

        client, err := jsonrpc.<span class="sgc-4">Dial</span>(<span class="sgc-3">"tcp"</span>, service)
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"dialing:"</span>, err)
        }
        <span class="sgc-8">// Synchronous call
</span> args := <span class="sgc-4">Args</span>{17, 8}
        <span class="sgc-2">var</span> reply <span class="sgc-6">int</span>
        err = client.<span class="sgc-4">Call</span>(<span class="sgc-3">"Arith.Multiply"</span>, args, &amp;reply)
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"arith error:"</span>, err)
        }
        fmt.<span class="sgc-4">Printf</span>(<span class="sgc-3">"Arith: %d*%d=%d\n"</span>, args.<span class="sgc-5">A</span>, args.<span class="sgc-5">B</span>, reply)

        <span class="sgc-2">var</span> quot <span class="sgc-4">Quotient</span>
        err = client.<span class="sgc-4">Call</span>(<span class="sgc-3">"Arith.Divide"</span>, args, ")
        <span class="sgc-2">if</span> err != nil {
                log.<span class="sgc-4">Fatal</span>(<span class="sgc-3">"arith error:"</span>, err)
        }
        fmt.<span class="sgc-4">Printf</span>(<span class="sgc-3">"Arith: %d/%d=%d remainder %d\n"</span>, args.<span class="sgc-5">A</span>, args.<span class="sgc-5">B</span>, quot.<span class="sgc-4">Quo</span>, quot.<span class="sgc-4">Rem</span>)

}
</span></code></pre>

  <h3 id="heading_id_12">JSON RPC server</h3>
  <h3 id="heading_id_12">JSON RPC 服务器</h3>

  <p class="en">A version of the server that uses JSON encoding is</p>
  <p class="zh">JSON版的服务器代码如下</p>
  <pre><code><span class="sgc-7">
<span class="sgc-8">/* JSONArithServer
 */
</span>
<span class="sgc-2">package</span> main

<span class="sgc-2">import</span> (
        <span class="sgc-3">"fmt"</span>
        <span class="sgc-3">"net/rpc"</span>
        <span class="sgc-3">"net/rpc/jsonrpc"</span>
        <span class="sgc-3">"os"</span>
        <span class="sgc-3">"net"</span>
        <span class="sgc-3">"errors"</span>
)
<span class="sgc-8">//import ("fmt"; "rpc"; "os"; "net"; "log"; "http")
</span>
<span class="sgc-2">type</span> <span class="sgc-4">Args</span> <span class="sgc-2">struct</span> {
        <span class="sgc-5">A</span>, <span class="sgc-5">B</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Quotient</span> <span class="sgc-2">struct</span> {
        <span class="sgc-4">Quo</span>, <span class="sgc-4">Rem</span> <span class="sgc-6">int</span>
}

<span class="sgc-2">type</span> <span class="sgc-4">Arith</span> <span class="sgc-6">int</span>

<span class="sgc-2">func</span> (t *<span class="sgc-4">Arith</span>) <span class="sgc-4">Multiply</span>(args *<span class="sgc-4">Args</span>, reply *<span class="sgc-6">int</span>) error {
        *reply = args.<span class="sgc-5">A</span> * args.<span class="sgc-5">B</span>
        <span class="sgc-2">return</span> nil
}

<span class="sgc-2">func</span> (t *<span class="sgc-4">Arith</span>) <span class="sgc-4">Divide</span>(args *<span class="sgc-4">Args</span>, quo *<span class="sgc-4">Quotient</span>) error {
        <span class="sgc-2">if</span> args.<span class="sgc-5">B</span> == 0 {
                <span class="sgc-2">return</span> errors.<span class="sgc-4">New</span>(<span class="sgc-3">"divide by zero"</span>)
        }
        quo.<span class="sgc-4">Quo</span> = args.<span class="sgc-5">A</span> / args.<span class="sgc-5">B</span>
        quo.<span class="sgc-4">Rem</span> = args.<span class="sgc-5">A</span> % args.<span class="sgc-5">B</span>
        <span class="sgc-2">return</span> nil
}

<span class="sgc-2">func</span> main() {

        arith := <span class="sgc-2">new</span>(<span class="sgc-4">Arith</span>)
        rpc.<span class="sgc-4">Register</span>(arith)

        tcpAddr, err := net.<span class="sgc-4">ResolveTCPAddr</span>(<span class="sgc-3">"tcp"</span>, <span class="sgc-3">":1234"</span>)
        checkError(err)

        listener, err := net.<span class="sgc-4">ListenTCP</span>(<span class="sgc-3">"tcp"</span>, tcpAddr)
        checkError(err)

<span class="sgc-8">        /* This works:
        rpc.Accept(listener)
        */
</span><span class="sgc-8"> /* and so does this:
         */
</span> <span class="sgc-2">for</span> {
                conn, err := listener.<span class="sgc-4">Accept</span>()
                <span class="sgc-2">if</span> err != nil {
                        <span class="sgc-2">continue</span>
                }
                jsonrpc.<span class="sgc-4">ServeConn</span>(conn)
        }

}

<span class="sgc-2">func</span> checkError(err error) {
        <span class="sgc-2">if</span> err != nil {
                fmt.<span class="sgc-4">Println</span>(<span class="sgc-3">"Fatal error "</span>, err.<span class="sgc-4">Error</span>())
                os.<span class="sgc-4">Exit</span>(1)
        }
}
</span></code></pre>

  <h2 id="heading_id_13" class="en">Conclusion</h2>
  <h2 id="heading_id_13" class="zh">总结</h2>

  <p class="en">RPC is a popular means of distributing applications. Several ways of doing it have been presented here. What is missing from Go is support for the currently fashionable (but extremely badly enginereed) SOAP RPC mechanism.</p>
  <p class="zh">RPC 是一个流行的分布应用的方法。这里展示了许多实现它的方法。Go所不支持的实现下很火的(却也是实现地很不好的) SOAP RPC 机制。</p>

  <p class="en">Copyright Jan Newmarch, jan@newmarch.name</p>
  <p class="zh">版权属于 Jan Newmarch, jan@newmarch.name</p>

  <p class="en">If you like this book, please contribute using Flattr <a class="FlattrButton sgc-9" href="http://jan.newmarch.name/go/index.html"></a><br />
  or donate using PayPal</p>
  <p class="zh">如果你喜欢这本书，请用我Flattr支持我 <a class="FlattrButton sgc-9" href="http://jan.newmarch.name/go/index.html"></a><br />
  或者用PayPal捐助我。</p>

  <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
    <input name="cmd" type="hidden" value="_s-xclick" /> <input name="encrypted" type="hidden" value="-----BEGIN PKCS7-----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-----END PKCS7----- " /> <input alt="PayPal - The safer, easier way to pay online." border="0" name="submit" src="https://www.paypalobjects.com/WEBSCR-640-20110401-1/en_AU/i/btn/btn_donateCC_LG.gif" type="image" /> <img alt="" border="0" height="1" src="https://www.paypalobjects.com/WEBSCR-640-20110401-1/en_AU/i/scr/pixel.gif" width="1" />
  </form>
</body>
</html>